{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "PdKwzEluDBN7"
      },
      "source": [
        "# Install openai-agents SDK"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "3QdkOviEB2ay",
        "outputId": "bae5bf21-2f09-4d45-84d2-91169dfc8ac5"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\u001b[?25l   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/116.9 kB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m116.9/116.9 kB\u001b[0m \u001b[31m5.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25h\u001b[?25l   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/129.3 kB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m129.3/129.3 kB\u001b[0m \u001b[31m7.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m100.4/100.4 kB\u001b[0m \u001b[31m4.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m44.4/44.4 kB\u001b[0m \u001b[31m1.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m72.0/72.0 kB\u001b[0m \u001b[31m3.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m62.5/62.5 kB\u001b[0m \u001b[31m3.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25h"
          ]
        }
      ],
      "source": [
        "!pip install -Uq openai-agents"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7yD91lz4DIAx"
      },
      "source": [
        "# Make your Notebook capable of running asynchronous functions.\n",
        "Both Jupyter notebooks and Python’s asyncio library utilize event loops, but they serve different purposes and can sometimes interfere with each other.\n",
        "\n",
        "The nest_asyncio library allows the existing event loop to accept nested event loops, enabling asyncio code to run within environments that already have an event loop, such as Jupyter notebooks.\n",
        "\n",
        "In summary, both Jupyter notebooks and Python’s asyncio library utilize event loops to manage asynchronous operations. When working within Jupyter notebooks, it’s essential to be aware of the existing event loop to effectively run asyncio code without conflicts."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {
        "id": "C8YXyIpiZ9v4"
      },
      "outputs": [],
      "source": [
        "import nest_asyncio\n",
        "nest_asyncio.apply()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wQsVowow7ihQ"
      },
      "source": [
        "# Config"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "XnusaX_RWF22"
      },
      "outputs": [],
      "source": [
        "from agents import (\n",
        "    AsyncOpenAI,\n",
        "    OpenAIChatCompletionsModel\n",
        ")\n",
        "from google.colab import userdata"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {
        "id": "oPvcFwItoKqw"
      },
      "outputs": [],
      "source": [
        "gemini_api_key = userdata.get(\"GEMINI_API_KEY\")\n",
        "\n",
        "\n",
        "# Check if the API key is present; if not, raise an error\n",
        "if not gemini_api_key:\n",
        "    raise ValueError(\"GEMINI_API_KEY is not set. Please ensure it is defined in your .env file.\")\n",
        "\n",
        "#Reference: https://ai.google.dev/gemini-api/docs/openai\n",
        "external_client = AsyncOpenAI(\n",
        "    api_key=gemini_api_key,\n",
        "    base_url=\"https://generativelanguage.googleapis.com/v1beta/openai/\",\n",
        ")\n",
        "\n",
        "model = OpenAIChatCompletionsModel(\n",
        "    model=\"gemini-2.0-flash\",\n",
        "    openai_client=external_client\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "y9LkW-F7nC3T"
      },
      "outputs": [],
      "source": [
        "from agents import set_tracing_disabled\n",
        "set_tracing_disabled(True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rWL7EnI_7mIF"
      },
      "source": [
        "# Context Management\n",
        "\n",
        "\n",
        "Context available locally to your code: this is data and dependencies you might need when tool functions run, during callbacks like on_handoff, in lifecycle hooks, etc.\n",
        "- You create any Python object you want. A common pattern is to use a dataclass or a Pydantic object.\n",
        "- You pass that object to the various run methods (e.g. Runner.run(..., **context=whatever**)).\n",
        "- All your tool calls, lifecycle hooks etc will be passed a wrapper object, - RunContextWrapper[T], where T represents your context object type which you can access via wrapper.context.\n",
        "- The most important thing to be aware of: every agent, tool function, lifecycle etc for a given agent run must use the same type of context.\n",
        "\n",
        "You can use the context for things like:\n",
        "- Contextual data for your run (e.g. things like a username/uid or other information about the user)\n",
        "- Dependencies (e.g. logger objects, data fetchers, etc)\n",
        "- Helper functions\n",
        "\n",
        "[Learning Reference](https://openai.github.io/openai-agents-python/context/)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ZRKxdIYbnL6w"
      },
      "source": [
        "# Local Context"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 15,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "uLTfHV0CnNgJ",
        "outputId": "bbfc362e-cfa7-4e56-f7a9-3ddfae14f374"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "The user is 30 years old and is from Pakistan.\n"
          ]
        }
      ],
      "source": [
        "import asyncio\n",
        "from dataclasses import dataclass\n",
        "\n",
        "from agents import Agent, RunContextWrapper, Runner, function_tool\n",
        "\n",
        "@dataclass\n",
        "class UserInfo1:\n",
        "    name: str\n",
        "    uid: int\n",
        "    location: str = \"Pakistan\"\n",
        "\n",
        "@function_tool\n",
        "async def fetch_user_age(wrapper: RunContextWrapper[UserInfo1]) -> str:\n",
        "    '''Returns the age of the user.'''\n",
        "    return f\"User {wrapper.context.name} is 30 years old\"\n",
        "\n",
        "@function_tool\n",
        "async def fetch_user_location(wrapper: RunContextWrapper[UserInfo1]) -> str:\n",
        "    '''Returns the location of the user.'''\n",
        "    return f\"User {wrapper.context.name} is from {wrapper.context.location}\"\n",
        "\n",
        "async def main():\n",
        "    user_info = UserInfo1(name=\"Muhammad Qasim\", uid=123)\n",
        "\n",
        "    agent = Agent[UserInfo1](\n",
        "        name=\"Assistant\",\n",
        "        tools=[fetch_user_age,fetch_user_location],\n",
        "        model=model\n",
        "    )\n",
        "\n",
        "    result = await Runner.run(\n",
        "        starting_agent=agent,\n",
        "        input=\"What is the age of the user? current location of his/her?\",\n",
        "        context=user_info,\n",
        "    )\n",
        "\n",
        "    print(result.final_output)\n",
        "    # The user John is 47 years old.\n",
        "\n",
        "if __name__ == \"__main__\":\n",
        "    asyncio.run(main())"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
